package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMpper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishMpper dishMpper;

    @Override
    public R add(Category category) {
        int i = categoryMapper.insert(category);
        return R.success("添加成功");
    }

    @Override
    public R findPage(Integer page, Integer pageSize) {
        Page<Category> p = new Page<>();
        p.setCurrent(page);
        p.setSize(pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        Page<Category> page1 = categoryMapper.selectPage(p, wrapper);
        return R.success(page1);
    }

    @Override
    public R removeById(Long id) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, id);
        List<Dish> dishes = dishMpper.selectList(wrapper);
        if (dishes.size() > 0) {
            return R.error("菜品下有菜不能删除");
        }
        LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Setmeal::getCategoryId, id);
        List<Setmeal> setmeals = setmealMapper.selectList(wrapper1);
        if (setmeals.size() > 0) {
            return R.error("套餐下有菜不能删除");
        }
        categoryMapper.deleteById(id);
        return R.success("删除成功");
    }

    @Override
    public R findList(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type!=null,Category::getType,type);
        List<Category> list = categoryMapper.selectList(wrapper);
        return R.success(list);
    }
}
